package com.xxd.algo.newcode.mid02.class04;

import java.util.HashMap;

/**
 * @author: XiaoDong.Xie
 * @create: 2021-10-16 11:46
 */
public class Code01_ReceiveAndPrintOrderLine {

    public static class Node {
        String info;
        Node next;

        public Node(String info) {
            this.info = info;
        }
    }

    public static class messageBox {
        private HashMap<Integer, Node> headMap;
        private HashMap<Integer, Node> tailMap;
        int waitPoint = 1;

        public messageBox() {
            this.headMap = new HashMap<>();
            this.tailMap = new HashMap<>();
        }


        /**
         * 接受一个值
         *
         * @param info
         * @param num
         */
        public void receive(String info, int num) {
            if (num < 1) {
                return;
            }
            Node cur = new Node(info);
            headMap.put(num, cur);
            tailMap.put(num, cur);

            if (tailMap.containsKey(num - 1)) {
                tailMap.get(num - 1).next = cur;
                tailMap.remove(num - 1);
                headMap.remove(num);
            }

            if (headMap.containsKey(num + 1)) {
                cur.next = headMap.get(num + 1);
                headMap.remove(num + 1);
                tailMap.remove(num);
            }

            if (num == waitPoint) {
                print();
            }
        }

        private void print() {
            Node node = headMap.get(waitPoint);
            headMap.remove(waitPoint);
            while (node != null) {
                System.out.println(node.info + " ");
                node = node.next;
                waitPoint++;
            }
            tailMap.remove(waitPoint - 1);
            System.out.println();
        }
    }
}
